package it.aekidna.cleverplatypus.workflow.template
{
	import flash.utils.getQualifiedClassName;
	
	import it.aekidna.cleverplatypus.mediator.CommandAsyncToken;
	import it.aekidna.cleverplatypus.mediator.CommandEvent;
	import it.aekidna.cleverplatypus.workflow.AbstractWorkflowTask;
	import it.aekidna.cleverplatypus.workflow.IWorkflowTask;
	import it.aekidna.cleverplatypus.workflow.WorkflowEvent;
	
	import mx.core.EventPriority;
	import mx.logging.ILogger;
	import mx.logging.Log;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	[Event(
		name="result",
		type="mx.rpc.events.ResultEvent")]

	[Event(
		name="fault",
		type="mx.rpc.events.FaultEvent")]

	public class PerformAsyncCommandTask extends AbstractWorkflowTask
	{
       protected static const LOGGER : ILogger =
            Log.getLogger( getQualifiedClassName( PerformAsyncCommandTask ).replace(/:+/g, "." ) );
		
		[Bindable]
		public var commandEventName : String;
		public var commandParameters : Object;
		
		
		override public function begin() : void
		{
			var token : CommandAsyncToken = 
				CommandEvent.createWithNamedParams( commandEventName, commandParameters ).dispatch();
			if( token )
			{
				token.addEventListener( ResultEvent.RESULT, onResult, false, EventPriority.DEFAULT_HANDLER );
				token.addEventListener( FaultEvent.FAULT, onFault, false, EventPriority.DEFAULT_HANDLER );
			}
			else
			{
				LOGGER.info( "CommandEvent '{0}' has been dispatched and the complete() method is been invoked straight away since the mediated method does not return a CommandAsyncToken", commandEventName );
				complete();
			}
		}
		
		
		public function onResult( inEvent : ResultEvent ) : void
		{
			dispatchEvent( inEvent );
			if( !inEvent.isDefaultPrevented() )
				complete();
		}
		
		public function onFault( inEvent : FaultEvent ) : void
		{
			dispatchEvent( new WorkflowEvent( WorkflowEvent.FAULT, inEvent.fault.toString() ) );
			if( !inEvent.isDefaultPrevented() )
				fail( name + " Failed" );
		}
		
	}
}